package org.example.new_hbps_backend_reconstruction.controller.patient;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.new_hbps_backend_reconstruction.common.results.R;
import org.example.new_hbps_backend_reconstruction.entity.PatientAvatarEntity;
import org.example.new_hbps_backend_reconstruction.service.PatientAvatarService;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * @author Gao zihan
 * @date 2025年10月16日
 * @description 患者头像管理控制器
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/patient/avatar")
@Tag(name = "患者头像管理", description = "提供患者头像上传、查询、删除等接口")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
@Slf4j
public class PatientAvatarController {

    private final PatientAvatarService patientAvatarService;

    @Operation(summary = "上传患者头像", description = "上传患者头像文件到OSS并保存到数据库")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "上传成功"),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping("/upload")
    //TODO:参考PatientBaseController有权限控制，但是没有具体实现，暂时注释
    //@PreAuthorize("@pms.hasPermission('patient_avatar_upload')")
    public R<PatientAvatarEntity> uploadAvatar(
            @Parameter(description = "患者ID", required = true) @RequestParam("patientUid") Long patientUid,
            @Parameter(description = "头像文件", required = true) @RequestParam("file") MultipartFile file) {
        try {
            log.info("开始上传患者头像，患者ID: {}, 文件名: {}", patientUid, file.getOriginalFilename());
            PatientAvatarEntity avatar = patientAvatarService.uploadAvatar(patientUid, file);
            return R.ok(avatar, "头像上传成功");
        } catch (IllegalArgumentException e) {
            log.warn("头像上传参数错误: {}", e.getMessage());
            return R.failed(e.getMessage());
        } catch (Exception e) {
            log.error("头像上传失败", e);
            return R.failed("头像上传失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取患者当前头像", description = "获取患者当前使用的头像信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "404", description = "未找到头像")
    })
    @GetMapping("/current/{patientUid}")
    //@PreAuthorize("@pms.hasPermission('patient_avatar_view')")
    public R<PatientAvatarEntity> getCurrentAvatar(
            @Parameter(description = "患者ID", required = true) @PathVariable("patientUid") Long patientUid) {
        try {
            PatientAvatarEntity avatar = patientAvatarService.getCurrentAvatar(patientUid);
            if (avatar == null) {
                return R.failed("未找到患者头像");
            }
            return R.ok(avatar, "当前头像获取成功");
        } catch (Exception e) {
            log.error("获取患者当前头像失败，患者ID: {}", patientUid, e);
            return R.failed("获取头像失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取患者头像历史", description = "获取患者所有头像历史记录")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功")
    })
    @GetMapping("/history/{patientUid}")
    //@PreAuthorize("@pms.hasPermission('patient_avatar_view')")
    public R<List<PatientAvatarEntity>> getAvatarHistory(
            @Parameter(description = "患者ID", required = true) @PathVariable("patientUid") Long patientUid) {
        try {
            List<PatientAvatarEntity> avatarHistory = patientAvatarService.getAvatarHistory(patientUid);
            return R.ok(avatarHistory, "头像历史获取成功");
        } catch (Exception e) {
            log.error("获取患者头像历史失败，患者ID: {}", patientUid, e);
            return R.failed("获取头像历史失败: " + e.getMessage());
        }
    }

    @Operation(summary = "删除头像", description = "删除指定的头像记录（不能删除当前使用的头像）")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "400", description = "不能删除当前头像")
    })
    @DeleteMapping("/{avatarId}")
    //@PreAuthorize("@pms.hasPermission('patient_avatar_delete')")
    public R<Boolean> deleteAvatar(
            @Parameter(description = "头像ID", required = true) @PathVariable("avatarId") Long avatarId) {
        try {
            boolean result = patientAvatarService.deleteAvatar(avatarId);
            return R.ok(result, result ? "头像删除成功" : "头像删除失败");
        } catch (IllegalArgumentException e) {
            log.warn("删除头像参数错误: {}", e.getMessage());
            return R.failed(e.getMessage());
        } catch (Exception e) {
            log.error("删除头像失败，头像ID: {}", avatarId, e);
            return R.failed("删除头像失败: " + e.getMessage());
        }
    }

    @Operation(summary = "设置默认头像", description = "为患者设置默认头像")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "设置成功")
    })
    @PostMapping("/default/{patientUid}")
    //@PreAuthorize("@pms.hasPermission('patient_avatar_edit')")
    public R<Boolean> setDefaultAvatar(
            @Parameter(description = "患者ID", required = true) @PathVariable("patientUid") Long patientUid) {
        try {
            boolean result = patientAvatarService.setDefaultAvatar(patientUid);
            return R.ok(result, result ? "默认头像设置成功" : "默认头像设置失败");
        } catch (Exception e) {
            log.error("设置默认头像失败，患者ID: {}", patientUid, e);
            return R.failed("设置默认头像失败: " + e.getMessage());
        }
    }
}